/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bitcar.platform.person.action;

import com.bitcar.common.constvalues.ConstValues;
import com.bitcar.common.constvalues.ConstValues.Status;
import com.bitcar.platform.person.StatusForm;
import com.bitcar.platform.person.model.DailyReport;
import com.bitcar.platform.person.model.ReportDetail;
import com.bitcar.platform.person.service.PersonService;
import com.bitcar.platform.system.model.User;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.dozer.spring.DozerBeanMapperFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

/**
 *
 * @author shd
 */
@Controller
@RequestMapping("/Person")
@SessionAttributes("user")
public class PersonController {

    private final Log log = LogFactory.getLog(PersonController.class);
    private PersonService personService;

    @Autowired
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    public PersonController() {
        log.info("init controller");
    }

    @RequestMapping(value = "/personIndex.do", method = RequestMethod.GET)
    public String personIndex(ModelMap model, @ModelAttribute("user") User user) {

        try {
            Date start = DateUtils.truncate(new Date(), Calendar.MONTH);
            Date end = DateUtils.addDays(DateUtils.addMonths(start, 1), -1);
            List<ReportDetail> list = personService.getDailyReportByUserid(user.getId(),
                    start, end);
            ObjectMapper om = new ObjectMapper();
            om.getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
            StringWriter sw = new StringWriter();
            JsonGenerator jg = new JsonFactory().createJsonGenerator(sw);
            
            om.writeValue(jg, list);

            model.addAttribute("detaillist", sw.toString());
            
            int statuscnt=Status.values().length;
            model.addAttribute("statuscnt",statuscnt);
            return "/daily/dailyreport";
        } catch (Exception ex) {
            log.error("toPersonIndex", ex);
            return ConstValues.COMMONEXCEPTION_KEY;
        }
    }
    

    /**
     * 填写某一天的工作内容时，要考虑新增或者调出当天的日报基本信息，主要获取的是id
     * @param resp
     * @param dailydate 过去的选中的一天的日期，is null则是当天时间
     * @param dailyid   已经存在的dailyid
     * @param model
     * @return 
     */
    @RequestMapping(value = "/toAddDailyReport.do", method = RequestMethod.GET)
    public @ResponseBody
    DailyReport toAddDailyReport(HttpServletResponse resp, @RequestParam("dailydate") String dailydate,
            ModelMap model, @ModelAttribute("user") User u) {
        DailyReport daily = new DailyReport();
        Date start = new Date(NumberUtils.toLong(dailydate));
        if (start == null) {    //当天的0点 最早时间
            start = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
        }
        try {
            daily.setUserid(u.getId());
            daily.setReportdate(DateUtils.truncate(start, Calendar.DAY_OF_MONTH));
            //daily.setTitle("工作日报");
            personService.saveDailyReport(daily);
            return daily;

        } catch (Exception ex) {
            log.error("toAddDailyReport", ex);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }
    }

    /**
     * 进入adddailyreport页面以后就直接新增一条当天的详细工作内容，然后返回到日历页面
     * 
     * @param model
     * @param detail
     * @return 
     */
    @RequestMapping(value = "/addDailyReportItem.do", method = RequestMethod.POST)
    public @ResponseBody
    ReportDetail addDailyReportItem(HttpServletResponse resp, ModelMap model, ReportDetail detail) {
        try {
            personService.saveReportDetail(detail);
            return detail;
        } catch (Exception ex) {
            log.error("addDailyReportItem", ex);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }

    }
    
    
      @RequestMapping(value = "/updateDailyReportItem.do", method = RequestMethod.POST)
    public @ResponseBody
    ReportDetail updateDailyReportItem(HttpServletResponse resp, ModelMap model, ReportDetail detail) {
        try {
            personService.updateReportDetail(detail);
            return detail;
        } catch (Exception ex) {
            log.error("addDailyReportItem", ex);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }

    }

    /**
     * 获取定义的status的对应值
     * @param resp
     * @param status    
     * @return 前台进度条的状态，对应的index能够在status中存在对应项
     */
    @RequestMapping(value = "/getReportStatus.do", method = RequestMethod.GET)
    public @ResponseBody
    StatusForm getReportDetailStatus(HttpServletResponse resp, @RequestParam("status") String status) {
        int idx=NumberUtils.toInt(status);
        Status st=Status.values()[NumberUtils.toInt(status)];
        StatusForm sf=new StatusForm(idx,st.name(),st.getColor(),st.getZhcnName());
        return sf;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        if (binder.getTarget() instanceof ReportDetail) {
            binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm"), true));
            
            //binder.registerCustomEditor(Date.class,"end",new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));

        }
    }
}
